﻿using Admin2024.Domain.Entity.System;
using Admin2024.Domain.IDomainService.System.IRoleService;
using Admin2024.Domain.Interface;
using Admin2024.Domain.ObjValue;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin2024.Domain.DomainService.System.RoleService
{
    public class RolePermissionService : IRolePermissionService
    {
        private readonly IRepository<AppRole> RoleRep;
        private readonly IRepository<AppPermission> PermissionRep;

        private readonly IRepository<AppRolePermission> RolePermissionRep;
        public RolePermissionService(IRepository<AppRole> roleRep, IRepository<AppPermission> permissionRep, IRepository<AppRolePermission> rolePermissionRep)
        {
            RoleRep = roleRep;
            PermissionRep = permissionRep;
            RolePermissionRep = rolePermissionRep;
        }

        public async Task<DomainResult<string>> CreatePermission(Guid roleId, Guid PerId)
        {
            var Role = await RoleRep.GetByIdAsync(roleId);
            var Per = await PermissionRep.GetByIdAsync(PerId);

            //1 查找是否存在
            if (Per != null && Role != null)
            {

                var appRolePermission = new AppRolePermission(roleId, PerId);
                await RolePermissionRep.CreateAsync(appRolePermission);
                return DomainResult<string>.Success("分配角色成功");

            }

            return DomainResult<string>.Error("分配角色失败");
        }

        public async Task<DomainResult<string>> DeletePermission(Guid roleId, Guid PerId)
        {
            var rolePer = RolePermissionRep.Table.Where(item => item.AppRoleId == roleId && item.AppPermissionId == PerId).FirstOrDefault();
            //1 查找是否存在
            if (rolePer !=null)
            {
                await RolePermissionRep.DeleteAsync(rolePer.Id);
                return DomainResult<string>.Success("移除角色权限成功");

            }

            return DomainResult<string>.Error("分配角色失败");
        }

        //获取角色里的所有权限

        public async Task<DomainResult<List<AppPermission>>> GetListRolePermission(Guid roleId)
        {
           var role = await RoleRep.GetByIdAsync(roleId);
           
           var rolePer = RolePermissionRep.Table.Where(item => item.AppRoleId == roleId);

            var appPermission = new  List<AppPermission>();
            //获取所有权限
            foreach (var item in rolePer)
            {
                //var per = PermissionRep.Table.Where(x => x.Id == item.AppPermissionId);
                //role.AllocatePermission(per)
                
            }
            return DomainResult<List<AppPermission>>.Success(appPermission);

            
        }
    }
}
